package org.sixtynine.stock.service.business;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.sixtynine.stock.Constants;
import org.sixtynine.stock.cache.CompanyDto;
import org.sixtynine.stock.entity.BaseEntity;
import org.sixtynine.stock.entity.Company;
import org.sixtynine.stock.entity.CompanyDocument;
import org.sixtynine.stock.entity.IntradayShareData;
import org.sixtynine.stock.entity.SubSector;
import org.sixtynine.stock.result.ShareResult;
import org.sixtynine.stock.util.ComDoc;

/**
 * @author Thilan
 * 
 */
public class StockUtil {

	private StockUtil() {

	}

	private static Logger logger = Logger.getLogger(StockUtil.class);

	/**
	 * @param code
	 * @param double value
	 * @return whether the value is grater than or lesser than given code return
	 *         true or false
	 */
	public static boolean filterValues(String code, double value) {

		if (code != null && !code.equals("-1")) {
			// from criteria send 0-10 pattern and split it using "-"
			String[] parts = code.split("-");
			// from the parts of items - value and + value check
			String[] firstPart = parts[0].split("_");
			String[] secondPart = parts[1].split("_");

			if (firstPart.length < 2 && secondPart.length < 2) {
				if (parts[1].equalsIgnoreCase(Constants.FILTER_DOUBLE_MAX)) {
					if (value > Integer.parseInt(parts[0])) {
						return true;
					}

				} else if (parts[0]
						.equalsIgnoreCase(Constants.FILTER_DOUBLE_MIN)) {
					if (value < Integer.parseInt(parts[1])) {
						return true;
					}

				} else if (!parts[1]
						.equalsIgnoreCase(Constants.FILTER_DOUBLE_MAX)
						&& !parts[0]
								.equalsIgnoreCase(Constants.FILTER_DOUBLE_MIN)) {
					if (value > Integer.parseInt(parts[0])
							&& value < Integer.parseInt(parts[1])) {
						return true;
					}
				}

				return false;
			} else {
				if (firstPart[0].equalsIgnoreCase(Constants.FILTER_NAGATIVE)
						|| secondPart[0]
								.equalsIgnoreCase(Constants.FILTER_NAGATIVE)) {
					// check whether negative value
					if (firstPart[1]
							.equalsIgnoreCase(Constants.FILTER_DOUBLE_MIN)
							&& !secondPart[1]
									.equalsIgnoreCase(Constants.FILTER_DOUBLE_MAX)) {
						if (value < (Integer.parseInt(secondPart[1])) * -1) {
							return true;
						}

					}
					if (secondPart[1]
							.equalsIgnoreCase(Constants.FILTER_DOUBLE_MAX)
							&& !firstPart[1]
									.equalsIgnoreCase(Constants.FILTER_DOUBLE_MIN)) {

						if (value > (Integer.parseInt(secondPart[0]) * -1)) {
							return true;
						}

					}
					if (!secondPart[1]
							.equalsIgnoreCase(Constants.FILTER_DOUBLE_MAX)
							&& !firstPart[1]
									.equalsIgnoreCase(Constants.FILTER_DOUBLE_MIN)) {

						if (value > (Integer.parseInt(secondPart[0]) * -1)
								&& value < (Integer.parseInt(firstPart[0]) * -1)) {
							return true;
						}

					}
					return false;

				}
			}
		}
		return true;
	}

	public static boolean like(String company, String search) {
		String companyName = company.toUpperCase();
		String searchText = search.toUpperCase();

		return companyName.contains(searchText);
	}

	public static String getFileName(String fileName) {
		String lastFileName = null;
		if (fileName != null) {
			String nameArry[] = fileName.split("_", 2);
			String name = nameArry[1];
			String lastName[] = name.split("\\.", 2);
			lastFileName = lastName[0];
		}
		return lastFileName;
	}

	/**
	 * TODO, add comment - describe what this method is doing
	 * 
	 * @param subSectorCode
	 * @param company
	 * @return
	 */
	public static boolean isSubSectorMatched(String subSectorCode,
			Company company) {
		Set<SubSector> compSub = (Set<SubSector>) company.getSubSectors();
		boolean isSubSec = false;
		if (!compSub.isEmpty() && subSectorCode != null) {
			for (SubSector subSector : compSub) {
				if (subSector.getCode().equals(subSectorCode)) {
					isSubSec = true;
				}
			}
		}

		return isSubSec;
	}

	/**
	 * @param code
	 * @return true if value is selected in the drop down, false otherwise
	 */
	public static boolean isDropdownValueSelected(String code) {
		return (code != null && !code.equals(Constants.DROPDOWN_ANY_OPITON));

	}

	public static String getEncryptedCode(String password, String merchantId,
			String acqId, String orderId, String price, String currencyCode) {

		String sha1 = null;
		if (merchantId != null && acqId != null && orderId != null
				&& price != null && currencyCode != null) {
			String hashTo = password + merchantId + acqId + orderId + price
					+ currencyCode;
			try {
				MessageDigest crypt = MessageDigest.getInstance("SHA-1");
				crypt.reset();
				crypt.update(hashTo.getBytes("UTF-8"));
				crypt.digest();
				sha1 = hexEncode(crypt.digest());
			} catch (NoSuchAlgorithmException e) {
				logger.error(e.getMessage());
			} catch (UnsupportedEncodingException e) {
				logger.error(e.getMessage());
			}

		}

		return sha1;

	}

	static private String hexEncode(byte[] aInput) {
		StringBuilder result = new StringBuilder();
		char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };
		for (int idx = 0; idx < aInput.length; ++idx) {
			byte b = aInput[idx];
			result.append(digits[(b & 0xf0) >> 4]);
			result.append(digits[b & 0x0f]);
		}
		return result.toString();
	}

	public static String getEncryptedUrl(String userCategory, String userEmail,
			String ownerCategory) {

		String sha1 = null;
		if (userCategory != null && userEmail != null && ownerCategory != null) {
			String hashTo = userCategory + userEmail + ownerCategory;
			try {
				MessageDigest crypt = MessageDigest.getInstance("SHA-1");
				crypt.reset();
				crypt.update(hashTo.getBytes("UTF-8"));
				crypt.digest();
				sha1 = hexEncode(crypt.digest());
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}

		return sha1;

	}

	public static double calculateOneDayVolatality(
			IntradayShareData currentShare) {
		double volataliti = 0;
		if (currentShare.getLow() != 0 && currentShare.getHigh() != 0) {
			volataliti = (currentShare.getHigh() / currentShare.getLow() - 1) * 100;
		}

		return volataliti;
	}

	public static void setCompanyDoc(CompanyDto companyDto,
			ShareResult shareResult) {
		List<BaseEntity> companyDocList = companyDto.getCompanyDocument();
		List<ComDoc> companyDocuments = new ArrayList<>();
		if (companyDocList != null) {
			for (BaseEntity baseEntity : companyDocList) {
				CompanyDocument companyDoc = (CompanyDocument) baseEntity;
				ComDoc compDocu = new ComDoc(companyDoc.getName(),
						companyDoc.getFileName());
				companyDocuments.add(compDocu);
			}
			shareResult.setComanyDocument(companyDocuments);
		}

	}

}
